﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using OrchardSystemServer.Config;
using OrchardSystemServer.Database;

namespace OrchardSystemServer
{
    public partial class Setting : Form
    {
        public Setting()
        {
            InitializeComponent();
            if (DbConfig.Config != null)
            {
                textBoxServer.Text=DbConfig.Config.Server;
                textBoxDatabase.Text = DbConfig.Config.Database;
                textBoxUser.Text = DbConfig.Config.Uid;
                textBoxPassword.Text = DbConfig.Config.Password;
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (CheckEmpty()) { MessageBox.Show("所有输入均不能输入不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop); }
            else
            {
                DbConfig config = new DbConfig(textBoxServer.Text, textBoxDatabase.Text, textBoxUser.Text, textBoxPassword.Text);
                MySQLHelper.SetConnectString(config.GetDbConnectString());
                MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
        }


        public bool CheckEmpty()
        {
            bool flag = false;
            if (textBoxDatabase.Text.Trim() == "" || textBoxServer.Text.Trim() == "" || textBoxUser.Text.Trim() == "" || textBoxPassword.Text.Trim() == "")
            {
                flag = true;
            }
            return flag;
        }

        private void buttonTestConnection_Click(object sender, EventArgs e)
        {
            bool flag = false;
            if (CheckEmpty()) { MessageBox.Show("所有输入均不能输入不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop); }
            else
            {
                DbConfig config = new DbConfig(textBoxServer.Text, textBoxDatabase.Text, textBoxUser.Text, textBoxPassword.Text);

                MySqlConnection connection = new MySqlConnection(config.GetDbConnectString());
                try
                {

                    connection.Open();
                    flag = true;
                }
                catch (MySqlException ex)
                {
                    flag = false;
                }
                catch (Exception ex)
                {
                    flag = false;
                }
                finally
                {
                    connection.Close();
                }
            }
            if (flag)
            {
                MessageBox.Show("连接成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("数据库连接失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }
    }
}
